package com.mc.util;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.client.utils.URIBuilder;

public class StringUtil {
	/**
	 * 为url添加经urlencode(utf-8)的参数
	 *
	 * @param url
	 * @param param
	 * @return 添加参数后的url
	 * @throws URISyntaxException
	 * @throws UnsupportedEncodingException
	 */
	public static final String addUtf8Parm2Url(String url, Map<String, String> param) throws URISyntaxException, UnsupportedEncodingException {
		String ret = url;
		if (param != null) {
			URIBuilder builder = new URIBuilder(url);
			for (Entry<String, String> e : param.entrySet()) {
				builder = builder.addParameter(URLEncoder.encode(e.getKey(), "UTF-8"), URLEncoder.encode(e.getValue(), "UTF-8"));
			}
			ret = builder.build().toString();
		}
		return ret;
	}

	/**
	 * 判断当前时间是否在服务时间
	 *
	 *
	 * @param startTime
	 * @param endTime
	 * @return
	 * @throws ParseException
	 */
	public static final boolean onService(String startTime, String endTime) throws ParseException {
		boolean on = false;
		String day = DateFormatUtils.format(new Date(), "yyyyMMdd");
		String time1 = StringUtils.leftPad(startTime, 6, '0');
		String time2 = StringUtils.leftPad(endTime, 6, '0');
		Date d1 = DateUtils.parseDate(day + time1, "yyyyMMddHHmmSS");
		Date d2 = DateUtils.parseDate(day + time2, "yyyyMMddHHmmSS");
		Date d3 = new Date();
		// 跨天
		if (d1.getTime() > d2.getTime()) {
			d2 = DateUtils.addDays(d2, 1);
		}
		on = d3.getTime() > d1.getTime();
		on &= d3.getTime() < d2.getTime();

		return on;
	}

	/**
	 * 字符串转简单HTML文档
	 *
	 * @param in
	 * @return
	 */
	public static final String toHtml(String in) {
		StringBuffer html = new StringBuffer();
		html.append("<html>");
		html.append("<body>");
		html.append("<hr/>");
		in = in.replace("\r\n", "<br/>");
		in = in.replace("\n", "<br/>");
		in = in.replace("\t", "&emsp;");
		in = in.replace(" ", "&nbsp;");
		html.append(in);
		html.append("<hr/>");
		html.append("</body>");
		html.append("</html>");
		return html.toString();
	}
}
